import React, { useState, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  ChevronLeft,
  ChevronRight,
  Search,
  Plus,
  Edit,
  Copy,
  Trash2,
  MoreHorizontal,
  Search as SearchIconEmpty,
} from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Badge } from "@/components/ui/badge";
import MethodTemplateForm from "@/components/knowledge-base/MethodTemplateForm";

// 场景标签映射
const scenarioLabels = {
  highway: "高速公路",
  roadsOrdinary: "普通公路(封路)",
  electricPowerCircuit: "电力线路(停电)",
  powerLinesWithoutPowerOutage: "电力线路(不停电)",
  railwayOrdinary: "普通铁路",
  riverWay: "通航河流",
  others: "其他",
};

// 获取复杂度配置
const getComplexityConfig = (count) => {
  if (count <= 3)
    return {
      label: "简单",
      color: "bg-emerald-50 text-emerald-700 border border-emerald-100",
    };
  if (count <= 7)
    return {
      label: "中等",
      color: "bg-amber-50 text-amber-700 border border-amber-100",
    };
  return {
    label: "复杂",
    color: "bg-rose-50 text-rose-700 border border-rose-100",
  };
};

export default function MethodTemplates({
  methodTemplates,
  onSubmit,
  onDelete,
  onCopy,
  searchTerm,
  setSearchTerm,
  selectedScenario,
  setSelectedScenario,
  handleFilteredCountChange,
}) {
  const [showForm, setShowForm] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState(null);
  const [filteredTemplates, setFilteredTemplates] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);

  // 筛选数据
  useEffect(() => {
    let filtered = methodTemplates;

    if (searchTerm) {
      filtered = filtered.filter(
        (template) =>
          template.methodName
            ?.toLowerCase()
            .includes(searchTerm.toLowerCase()) ||
          template.methodCode
            ?.toLowerCase()
            .includes(searchTerm.toLowerCase()) ||
          template.description?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (selectedScenario !== "all") {
      filtered = filtered.filter(
        (template) =>
          template.applicableScenarios &&
          Array.isArray(template.applicableScenarios) &&
          template.applicableScenarios.includes(selectedScenario)
      );
    }

    setFilteredTemplates(filtered);
    handleFilteredCountChange("methods", filtered.length);
    setCurrentPage(1); // 筛选后重置页码
  }, [
    methodTemplates,
    searchTerm,
    selectedScenario,
    handleFilteredCountChange,
  ]);

  // 分页处理函数
  const handlePageChange = (pageNum) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  const handleItemsPerPageChange = (count) => {
    setItemsPerPage(count);
    setCurrentPage(1); // 切换每页条数时重置到第一页
  };

  // 计算分页数据
  const totalItems = filteredTemplates.length;
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredTemplates.slice(
    indexOfFirstItem,
    indexOfLastItem
  );

  // 渲染分页组件（与提供的模式保持一致）
  const renderPagination = () => (
    <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-4 py-3 border-t">
      <div className="text-sm text-gray-500">
        共 {totalItems} 条数据，显示
        {(currentPage - 1) * itemsPerPage + 1} 到
        {Math.min(currentPage * itemsPerPage, totalItems)} 条
      </div>
      <div className="flex items-center gap-2">
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="sm" className="h-8">
              每页 {itemsPerPage} 条
              <MoreHorizontal className="ml-2 h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {[5, 10, 20, 50].map((count) => (
              <DropdownMenuItem
                key={count}
                onClick={() => handleItemsPerPageChange(count)}
              >
                {count} 条/页
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        <div className="flex items-center gap-1">
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronLeft className="h-4 w-4" />
            <span className="sr-only">上一页</span>
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="icon"
                className="h-8 w-8"
                onClick={() => handlePageChange(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button
            variant="outline"
            size="icon"
            className="h-8 w-8"
            onClick={() => handlePageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            <ChevronRight className="h-4 w-4" />
            <span className="sr-only">下一页</span>
          </Button>
        </div>
      </div>
    </div>
  );

  const handleEdit = (template) => {
    setEditingTemplate(template);
    setShowForm(true);
    setTimeout(() => {
      const formElement = document.getElementById("method-template-form");
      if (formElement) {
        formElement.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }, 250);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingTemplate(null);
  };

  // 计算每个模板的资源统计
  const getTemplateStats = (template) => {
    const safeSteps = Array.isArray(template.constructionSteps)
      ? template.constructionSteps
      : [];
    const complexity = safeSteps.length;

    const materialCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.requiredMaterials)
          ? step.requiredMaterials.length
          : 0),
      0
    );
    const personnelCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.requiredPersonnel)
          ? step.requiredPersonnel.length
          : 0),
      0
    );
    const equipmentCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.requiredEquipment)
          ? step.requiredEquipment.length
          : 0),
      0
    );
    const vehicleCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.requiredVehicles)
          ? step.requiredVehicles.length
          : 0),
      0
    );
    const safetyMeasureCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.safetyMeasures) ? step.safetyMeasures.length : 0),
      0
    );
    const qualityMeasureCount = safeSteps.reduce(
      (sum, step) =>
        sum +
        (Array.isArray(step.qualityMeasures) ? step.qualityMeasures.length : 0),
      0
    );

    return {
      complexity,
      materialCount,
      personnelCount,
      equipmentCount,
      vehicleCount,
      safetyMeasureCount,
      qualityMeasureCount,
    };
  };

  return (
    <div className="space-y-4">
      {/* 搜索筛选区 */}
      <div className="flex flex-col md:flex-row gap-3 items-start md:items-center">
        <div className="relative flex-1 w-full">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索施工方法名称、代码或描述..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 h-10 border-gray-200 focus:border-blue-400 focus:ring-1 focus:ring-blue-400 transition-all"
          />
        </div>

        <Select value={selectedScenario} onValueChange={setSelectedScenario}>
          <SelectTrigger className="w-full md:w-[180px] h-10 border-gray-200">
            <SelectValue placeholder="所有场景" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">所有场景</SelectItem>
            <SelectItem value="highway">高速公路</SelectItem>
            <SelectItem value="roadsOrdinary">普通公路(封路)</SelectItem>
            <SelectItem value="electricPowerCircuit">电力线路(停电)</SelectItem>
            <SelectItem value="powerLinesWithoutPowerOutage">
              电力线路(不停电)
            </SelectItem>
            <SelectItem value="railwayOrdinary">普通铁路</SelectItem>
            <SelectItem value="riverWay">通航河流</SelectItem>
            <SelectItem value="others">其他</SelectItem>
          </SelectContent>
        </Select>

        <Button
          onClick={() => {
            setEditingTemplate(null);
            setShowForm(true);
          }}
          className="bg-blue-600 hover:bg-blue-700 h-10 px-4 transition-all shadow-sm hover:shadow"
        >
          <Plus className="w-4 h-4 mr-2" />
          新建方法模板
        </Button>
      </div>

      {/* 表单区域 */}
      {showForm && (
        <MethodTemplateForm
          template={editingTemplate}
          onSubmit={onSubmit}
          onCancel={handleCancel}
          id="method-template-form"
        />
      )}

      {/* 表格与分页区 */}
      {filteredTemplates.length > 0 ? (
        <div className="rounded-lg border border-gray-200 overflow-hidden shadow-sm">
          {/* 表格 */}
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 border-b border-gray-200">
                <TableRow>
                  <TableHead className="w-[200px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    方法名称
                  </TableHead>
                  <TableHead className="min-w-[220px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    描述
                  </TableHead>
                  <TableHead className="min-w-[100px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    适用场景
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-left text-sm font-semibold text-gray-700">
                    复杂度
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    步骤数
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    物料数
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    工种类别
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    工器具数
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    车辆数
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    安全措施
                  </TableHead>
                  <TableHead className="w-[80px] py-3 px-4 text-center text-sm font-semibold text-gray-700">
                    质量措施
                  </TableHead>
                  <TableHead className="w-[100px] py-3 px-4 text-right text-sm font-semibold text-gray-700">
                    操作
                  </TableHead>
                </TableRow>
              </TableHeader>

              <TableBody>
                {currentItems.map((template, idx) => {
                  const stats = getTemplateStats(template);
                  const complexityConfig = getComplexityConfig(
                    stats.complexity
                  );
                  const isEvenRow = (indexOfFirstItem + idx) % 2 === 0;
                  const descText = template.description || "暂无描述";

                  return (
                    <TableRow
                      key={template.id}
                      className={`
                     transition-colors duration-150
                        border-b border-gray-100 last:border-0
                      `}
                    >
                      <TableCell className="py-3 px-4">
                        <div className="font-medium text-gray-900">
                          {template.methodName || "未命名模板"}
                        </div>
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <div
                          className="text-gray-700 break-words max-w-[220px] 
                                    overflow-hidden text-ellipsis 
                                    line-clamp-2
                                    display: -webkit-box; display: box;
                                    cursor: help"
                          title={descText}
                        >
                          {descText}
                        </div>
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <div className="flex flex-wrap gap-1.5">
                          {Array.isArray(template.applicableScenarios) &&
                            template.applicableScenarios.map(
                              (scenario, sIdx) => (
                                <Badge
                                  key={sIdx}
                                  variant="secondary"
                                  className="text-xs bg-gray-100 text-gray-700 hover:bg-gray-200"
                                >
                                  {scenarioLabels[scenario] || scenario}
                                </Badge>
                              )
                            )}
                        </div>
                      </TableCell>
                      <TableCell className="py-3 px-4">
                        <Badge
                          className={`${complexityConfig.color} px-2 py-0.5 text-xs rounded-md border`}
                        >
                          {complexityConfig.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.complexity}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.materialCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.personnelCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.equipmentCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.vehicleCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.safetyMeasureCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-center text-gray-700">
                        {stats.qualityMeasureCount}
                      </TableCell>
                      <TableCell className="py-3 px-4 text-right">
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon"
                              className="h-8 w-8 text-gray-600 hover:text-blue-600 hover:bg-blue-50 transition-colors"
                            >
                              <MoreHorizontal className="w-4 h-4" />
                              <span className="sr-only">打开操作菜单</span>
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent
                            align="end"
                            className="w-[140px] border-gray-200"
                          >
                            <DropdownMenuItem
                              onClick={() => handleEdit(template)}
                              className="cursor-pointer hover:bg-blue-50 hover:text-blue-700"
                            >
                              <Edit className="w-4 h-4 mr-2" />
                              编辑
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => onCopy(template)}
                              className="cursor-pointer hover:bg-blue-50 hover:text-blue-700"
                            >
                              <Copy className="w-4 h-4 mr-2" />
                              复制
                            </DropdownMenuItem>
                            <DropdownMenuSeparator className="bg-gray-100" />
                            <DropdownMenuItem
                              onClick={() => onDelete(template.id)}
                              className="text-red-600 cursor-pointer hover:bg-red-50"
                            >
                              <Trash2 className="w-4 h-4 mr-2" />
                              删除
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>

          {/* 分页组件（使用统一模式） */}
          {renderPagination()}
        </div>
      ) : (
        <div className="text-center py-16 px-4 text-gray-500 border rounded-lg bg-gray-50 border-gray-200">
          <SearchIconEmpty className="w-10 h-10 mx-auto mb-4 text-gray-300" />
          <h3 className="text-lg font-medium text-gray-600 mb-2">
            没有找到匹配的施工方法模板
          </h3>
          <p className="text-sm text-gray-400">
            建议调整搜索关键词或筛选场景后重试
          </p>
        </div>
      )}
    </div>
  );
}
